package org.springframework.web.method.support;

import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.web.bin.annotation.UploadFile;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;

public class UploadFileMethodArgumentResolver implements HandlerMethodArgumentResolver {
    private final ParameterNameDiscoverer parameterDiscoverer = new LocalVariableTableParameterNameDiscoverer();    
    
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(UploadFile.class);
               //&& parameter.getParameterType().isAssignableFrom(MultipartFile.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory)
            throws Exception {
        parameter.initParameterNameDiscovery(parameterDiscoverer);
        
        String fileName = parameter.getParameterAnnotation(UploadFile.class).value();
        //MultipartFile multipartFile = getRequestMultipartFile(webRequest, fileName);
        
        return null; //multipartFile;
    }           
    
    /*private MultipartFile getRequestMultipartFile(NativeWebRequest webRequest, String fileName) throws IOException {
        HttpServletRequest nativeRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        MultipartHttpServletRequest multipartRequest = new DefaultMultipartHttpServletRequest(nativeRequest);
        
        Long helpdeskId = Long.valueOf(multipartRequest.getParameter("helpdeskId"));
        Long ownerId = Long.valueOf(multipartRequest.getParameter("ownerId"));
        
        org.springframework.web.multipart.MultipartFile springMultiPartFile = multipartRequest.getFile(fileName);        
        MultipartFile multiPartFile = new MultipartFile();
        
        multiPartFile.setHelpdeskId(helpdeskId);
        multiPartFile.setOwnerId(ownerId);
        multiPartFile.setContentType(springMultiPartFile.getContentType());
        multiPartFile.setContent(springMultiPartFile.getBytes());
        multiPartFile.setName(springMultiPartFile.getName());
        multiPartFile.setOriginalFileName(springMultiPartFile.getOriginalFilename());
        
        return multiPartFile;
    }*/  
}
